package com.mical.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class TokenStoreService {
    @Autowired

    private RedisTemplate<String, String> redisTemplate;

    // 用户登录时记录Token
    public void storeToken(String username, String token) {
        String key = "user:tokens:" + username;
        redisTemplate.opsForSet().add(key, token);
        redisTemplate.expire(key, 7, TimeUnit.DAYS); // 保持7天
    }

    // 清除用户所有Token
    public void clearAllTokens(String username) {
        String key = "user:tokens:" + username;
        Set<String> tokens = redisTemplate.opsForSet().members(key);
        tokens.forEach(token -> {
            redisTemplate.delete("invalid:" + token); // 清理黑名单
        });
        redisTemplate.delete(key);
    }

    // 检查Token有效性
    public boolean isTokenValid(String username, String token) {
        return !redisTemplate.hasKey("invalid:" + token) &&
                redisTemplate.opsForSet().isMember("user:tokens:" + username, token);
    }
}